package com.ifgi.sitcom.campusmapperNDrawer.fragments;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater;
import com.gamificationlibrary.model.Player;
import com.ifgi.sitcom.campusmapperNDrawer.R;
import com.ifgi.sitcom.campusmapperNDrawer.controllers.*;
import com.ifgi.sitcom.campusmapperNDrawer.dialogs.*;
import com.ifgi.sitcom.campusmapperNDrawer.dialogs.ExistingPlanDialog.ExistingPlanDialogListener;
import com.ifgi.sitcom.campusmapperNDrawer.indoordata.*;
import com.ifgi.sitcom.campusmapperNDrawer.io.*;
import com.ifgi.sitcom.campusmapperNDrawer.outdoordata.*;



/*
 * Allows to select the building and the floor where the floorplan is situated. 
 * Requests a list of all buildings from the triple store using 
 * TripleStoreConnector.queryBuildings(). Only buildings included in the list 
 * are allowed to be selected. It is mandatory to fill both, building and 
 * floor. After completion either ImageSourceActivity or ExistingPlanActivity 
 * (to be implemented) is called, depending on if there already exists data 
 * for the selected building and floor.
 */
public class ChooseLocationFragment extends SherlockFragment implements ExistingPlanDialogListener {
	
	public final static String EXTRA_BUILDING_NAME = "de.ifgi.sitcom.campusmapper.buildingName";
	public final static String EXTRA_FLOOR_NUMBER = "de.ifgi.sitcom.campusmapper.floorNumber";
	public final static String EXTRA_BUILDING_URI = "de.ifgi.sitcom.campusmapper.buildingURI";
	public final static String EXTRA_LOAD_FROM_SERVER = "de.ifgi.sitcom.campusmapper.loadFromServer";
	public final static String EXTRA_LOAD_LOCAL_DATA = "de.ifgi.sitcom.campusmapper.loadLocalData";

	
	// textView to select the floor level
	private AutoCompleteTextView mTextViewFloor;
	// progressCircle to be shown until Lodum data was loaded
	ProgressDialog mProgressDialog;
	
	
	// to be filled with the data loaded from Lodum
	
	
	private TextView mTextViewName;
	private String buildingName;
	private String buildingURI;
	
	@Override
	public void onCreate (Bundle savedInstanceState){
	    super.onCreate(savedInstanceState);
	    setHasOptionsMenu(true);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
	View rootView = inflater.inflate(R.layout.activity_building_information, container, false);
		
	
	getActivity().setTitle(R.string.title_activity_building_information);
	    Bundle b=getArguments();
		buildingName=b.getString(ChooseLocationFragment.EXTRA_BUILDING_NAME);
		buildingURI=b.getString(ChooseLocationFragment.EXTRA_BUILDING_URI);
		
		mTextViewFloor = (AutoCompleteTextView) rootView.findViewById(R.id.multiAutoCompleteTextView2);
		mTextViewFloor.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

				if (event != null){
					if (event.getAction() == KeyEvent.KEYCODE_ENTER ||
							event.getAction() == KeyEvent.ACTION_DOWN){


						onOk();
						return true;
					}
					
				}
				
				if(actionId == EditorInfo.IME_ACTION_DONE) {
					onOk();
					return true;
				}
				
				
				return false;
			}
		});
		
		mTextViewName= (TextView) rootView.findViewById(R.id.textView_buildingName);
		mTextViewName.setText(buildingName);
		
	
	return rootView;
	}
	
	
	

	
	
	

	private boolean isValid(){
		
		if (!isNetworkAvailable(getActivity())){
			Toast.makeText(getActivity(), getString(R.string.message_no_internet), Toast.LENGTH_SHORT).show();
		    return false;
		}
		
		if(mTextViewFloor.getText().toString().length() == 0) {
			Toast.makeText(getActivity(), getString(R.string.message_chose_building_and_floor), Toast.LENGTH_SHORT).show();
			return false;
		}
		
		return true;
	}
	
	
	public void launchImageSourceActivity() {
				
		ImageSourceFragment fragment = new ImageSourceFragment();
		Bundle b=new Bundle();
		b.putString(ChooseLocationFragment.EXTRA_BUILDING_NAME, buildingName);
		b.putString(ChooseLocationFragment.EXTRA_FLOOR_NUMBER, mTextViewFloor.getText().toString());
		b.putString(ChooseLocationFragment.EXTRA_BUILDING_URI, buildingURI);
		fragment.setArguments(b);
		
		android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
   	    ft.addToBackStack(null);
    	ft.commit();
	}
	
	
	
	
	

	

	  
	
	private void onOk(){
		if (! isValid()) return;
		
		/*
		 * check if there already exists data for the seleceted floor and building
		 * 
		 * if so, show dialog offering to edit existing data or to create new plan
		 */
		mProgressDialog = ProgressDialog.show(getActivity(),
				"Please, wait...",
				"Loading projects",
				true);
		
		new Thread(new Runnable() {
			public void run() {
				ArrayList<FloorPlan> floorPlans = getFloorPlans();
				mProgressDialog.dismiss();
				if (floorPlans != null && floorPlans.size() > 0){
					// show dialog
					showChoosePlanDialog(floorPlans);
				} else {
					launchImageSourceActivity();
				}
			}
		}).start();	  			
	}
	
	
	 private void showChoosePlanDialog(ArrayList<FloorPlan> floorPlans){
			
			 ExistingPlanDialog choosePlanDialogFragment = new ExistingPlanDialog();
			choosePlanDialogFragment.attachHandler(this);
			choosePlanDialogFragment.setFloorPlans(floorPlans);
			choosePlanDialogFragment.show(getActivity().getSupportFragmentManager(), "");

		 
		 
	 }
	 
	private ArrayList<FloorPlan> getFloorPlans(){
		
		RDFReader rdfReader = new RDFReader();
		ArrayList<FloorPlan> floorPlans = rdfReader.getFloorPlanList(buildingURI, mTextViewFloor.getText().toString(), buildingName);
		
		return floorPlans;
	}
	
	public static boolean isNetworkAvailable(Context context) 
	{
	    return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
	}
	
	 private void startMappingActivity(FloorPlan floorPlan){

			MappingFragment fragment = new MappingFragment();
			Bundle b=new Bundle();
			b.putString(ImageSourceFragment.EXTRA_SOURCE_URI, floorPlan.getSourceFloorPlanImageUri().toString());
			b.putString(ImageSourceFragment.EXTRA_CROPPED_URI, floorPlan.getCroppedFloorPlanImageUri().toString());
			b.putString(ChooseLocationFragment.EXTRA_BUILDING_NAME, floorPlan.getBuildingName());
			b.putString(ChooseLocationFragment.EXTRA_BUILDING_URI, floorPlan.getBuildingURI());
			b.putString(ChooseLocationFragment.EXTRA_FLOOR_NUMBER, Integer.toString(floorPlan.getFloorNumber()));
			b.putBoolean(ChooseLocationFragment.EXTRA_LOAD_FROM_SERVER, true);
			fragment.setArguments(b);
			
			android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
	        ft.replace(R.id.content_frame, fragment);
	   	    ft.addToBackStack(null);
	    	ft.commit();
	 }


	@Override
	public void onExistingPlanDialogPositiveClick(ExistingPlanDialog dialog) {
		final FloorPlan floorPlan = dialog.getSelectedPlan();
		
		if(floorPlan == null){
			// create new plan
			launchImageSourceActivity();
		} else {
			mProgressDialog = ProgressDialog.show(getActivity(),
					"Please, wait...",
					"Loading mapping",
					true);
			new Thread(new Runnable() {
				public void run() {

					// load floorplan data

					RDFReader rdfReader = new RDFReader();
					rdfReader.getFloorPlan(floorPlan);
					
					// save floorplan data on sd
					RDFWriter rdfCreater = new RDFWriter();
					rdfCreater.floorPlanToRDF(floorPlan); // will be written to temp.ttl in campusMapper on sd
					
					mProgressDialog.dismiss();
					
					// start mappig activity
					startMappingActivity(floorPlan);				
				}
			}).start();				
		}
		
		
	}

	@Override
	public void onExistingPlanDialogNegativeClick(ExistingPlanDialog dialog) {
		// do nothing		
	}


	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.building_information, menu);
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		 // handle item selection
		   switch (item.getItemId()) {
		   
		   case R.id.action_next:
				
				onOk();
				InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(mTextViewFloor.getWindowToken(), 0);
				return true;
		
		      default:
		    	 return super.onOptionsItemSelected(item);		
		   }
		}
}
